#include "BlackPinePlugin.h"
#include <dlfcn.h>
//#define DEBUG
static void* dlr;
static int plugin_num = 0;

BlackPinePlugin* new_plugin(const char* name, const char* path)
{
  BlackPinePlugin* (*creater)(void);
  std::string dlname = path;
  if (!dlname.empty() && dlname[dlname.size()-1] != '/') dlname += "/";
  dlname += name;
  //   dlname = dlname.substr(0, dlname.find_last_of("."));
#if defined(Linux) || defined(Freebsd) || defined(MaxOS)
  dlname += ".so";
#elif defined(Cygwin) || defined(MSWin32)
  dlname += ".dll";
#endif

#ifdef DEBUG
  std::cerr << "new_plugin (" << dlname  << ") ..." << std::endl;
#endif
  dlr = dlopen(dlname.c_str(), RTLD_LAZY);

  if(dlr == NULL){
    std::cerr << dlerror() << std::endl;
    return NULL;
  }
  creater = (BlackPinePlugin* (*)(void)) dlsym(dlr, "create_plugin");
  plugin_num++;
  return (*creater)();
}

void delete_plugin(BlackPinePlugin* p) {
#ifdef DEBUG
  std::cerr << "delete_plugin" << std::endl;
#endif
  delete p;
  plugin_num--;
  if (plugin_num == 0) {
#ifdef DEBUG
    std::cerr << "dlclose" << std::endl;
#endif
    dlclose(dlr);
  }
}
